package com.example.config;

import com.example.filter.JwtLoginTokenFilter;
import com.example.service.impl.AccountInfoServiceImpl;
import com.example.utils.Md5Utils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 定义一个SpringSecurity配置类，这个配置类继承WebSecurityConfigurerAdpter
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AccountInfoServiceImpl accountInfoService;

    @Resource
    private JwtLoginTokenFilter jwtLoginTokenFilter;

    //创建BCryptPasswordEncoder注入容器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Md5Utils();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * configure(AuthenticationManagerBuilder auth)方法的作用
     * 是通过设置UserDetailsService来指定如何获取用户的认证信息，
     * 以便在用户登录时进行认证。
     * 这样，Spring Security就能够根据你提供的认证方式，
     * 对用户进行身份验证和授权操作。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    //关闭csrf
                .csrf().disable()
                //不通过session获取SecurityContent
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口，允许匿名访问
                .antMatchers("/accountInfo/login").anonymous()//permitAll()方法，无论有没有登录都可以访问
                //除上面外的所有请求全部需要鉴证认证
                .anyRequest().authenticated();
        //添加Token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtLoginTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }


    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置认证方式，使用自定义的密码编码器
        auth.userDetailsService(accountInfoService);
    }

}

